package com.oristand.printer.address.util;

import com.oristand.printer.address.model.LabelDetail;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author chenkailiang
 * @date 2020/9/2
 */
public class FileUtil {

    /**
     * 匹配itemCode的正则
     */
    public static final Pattern PATTERN_ITEMCODE = Pattern.compile("INV:\\s*(\\S+)\\^FS");
    /**
     * 匹配销售平台订单号的正则
     */
    public static final Pattern PATTERN_ORDERID = Pattern.compile("REF:\\s*(\\S+)\\^FS");
    /**
     * 匹配trackingNumber的正则
     */
    public static final Pattern PATTERN_TRACKINGNUMBER_UPDATE = Pattern.compile("oritrk:(\\S+)\\^FS");

    /**
     * 从zpl文件中解析label列表
     *
     * @param file 文件
     * @return label列表
     */
    public static ObservableList<LabelDetail> getLabelDetailDataFromFile(File file){
        ObservableList<LabelDetail> list = null;
        try (FileInputStream inputStream = new FileInputStream(file)){
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            list = getLabelDetailFromString(new String(bytes));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;

    }

    /**
     * 从字符串中匹配label数据
     *
     * @param data 字符串
     * @return label列表
     */
    private static ObservableList<LabelDetail> getLabelDetailFromString(String data){
        ObservableList<LabelDetail> labelList = FXCollections.observableArrayList();
        String[] arr = data.split(Constants.ZPL_END_ESCAPE);
        int labelIndex = 1;
        for(int index = 0;index<arr.length;index++){
            //检查某个label下面的2张label,是不是S2S或者65 warning
            String temp = arr[index];
            if(temp.length()<50){
                continue;
            }
            String temp2 = "";
            if(index <arr.length-1){
                temp2 = arr[index+1];
            }
            String temp3 = "";
            if(index <arr.length-2){
                temp3 = arr[index+2];
            }
            LabelDetail labelDetail = getLabelDetailFromTempString(temp,labelIndex);
            int count1 = checkIsShippingLabel(temp);
            int count2 = checkIsShippingLabel(temp2);
            int count3 = checkIsShippingLabel(temp3);
            int count = count2+count3;
            //避免下1张label是shipping label而下2张label是s2s或65 warning
            if(count2 ==0 && labelDetail != null){
                count = 0;
            }
            if(count1==0 && labelDetail!=null){
                labelDetail.setAttachmentNumber(count);
                //用来from to方式打印，以免遗漏
                labelDetail.setLineNumber(index);
                labelList.add(labelDetail);
                labelIndex++;
            }
        }
        return labelList;
    }

    /**
     * 判断是否是加州65号法案或者S2S label
     * @param temp 字符串
     * @return int
     */
    private static int checkIsShippingLabel(String temp){
        if(StringUtils.isNotBlank(temp)){
            if(temp.contains(Constants.WARNING_LABEL) || (temp.contains(Constants.S2S_LABEL))){
                return 1;
            }
        }
        return 0;
    }

    /**
     * 从字符串中获取label对象
     * @param temp 字符串
     * @param index line_num
     * @return labelDetail
     */
    public static LabelDetail getLabelDetailFromTempString(String temp,int index){
        String trackingNumber = getPatternString(PATTERN_TRACKINGNUMBER_UPDATE,temp);
        if(trackingNumber!=null){
            trackingNumber = trackingNumber.replaceAll(Constants.SPACE,"");
        }
        String itemCode = getPatternString(PATTERN_ITEMCODE,temp);
        String orderId = getPatternString(PATTERN_ORDERID,temp);
        if(StringUtils.isNotBlank(trackingNumber) && StringUtils.isNotBlank(itemCode) && StringUtils.isNotBlank(orderId)){
            LabelDetail labelDetail = new LabelDetail(new SimpleStringProperty(index+""),new SimpleStringProperty(""),new SimpleStringProperty(""),new SimpleStringProperty(""));
            labelDetail.setItemCode(getPatternString(PATTERN_ITEMCODE,temp));
            labelDetail.setOrderId(getPatternString(PATTERN_ORDERID,temp));
            labelDetail.setTrackingNumber(trackingNumber);
            return labelDetail;
        }else{
            return null;
        }
    }


    /**
     * 获取指定正则表达式匹配的字符串
     *
     * @param pattern 正则
     * @param data 字符串
     * @return 匹配的字符串
     */
    public static String getPatternString(Pattern pattern,String data){
        Matcher matcher = pattern.matcher(data);
        if(matcher.find()){
            return matcher.group(1);
        }else{
            return null;
        }
    }

    /**
     * 从zpl文件读取内容
     * @param file file
     * @return string
     */
    public static String getStringFromZpl(File file){
        try (FileInputStream input = new FileInputStream(file)){
            int all = input.available();
            byte[] buffer = new byte[all];
            input.read(buffer);
            return new String(buffer);
        } catch (IOException e) {
            Platform.runLater(()->CommonMethodUtil.tipAlert(Constants.FILE_NOT_FOUND,e));
        }
        return null;
    }

    /**
     * 根据md5值查询数据库查看文件是否被打印过
     * @param file file
     * @return true/false
     */
    public static boolean filePrinting(File file){
        try {
            SqliteUtil sqliteUtil = new SqliteUtil(Constants.LOCAL_PRINT_RECORD);
            String md5 = DigestUtils.md5Hex(new FileInputStream(file));
            String sql = "select count(*) from printRecord where  md5 = '"+md5+"'";
            int printCount = sqliteUtil.executeQuery(sql);
            return printCount != 0;
        } catch (Exception e) {
            Platform.runLater(()->CommonMethodUtil.tipAlert(Constants.DATABASE_ERROR,e));
        }
        return false;

    }





}
